<?php
App::uses('AuthComponent', 'Controller/Component');

class User extends AppModel{

	public $name = 'User';
	public $hasMany = array(
			'Follower' => array(
					'className'     => 'Follow',
					'foreignKey'    => 'following_id',
					'conditions'    => '',
					'order'         => '',
					'limit'         => '',
					'dependent'     => false
			),
			'Following' => array(
					'className'     => 'Follow',
					'foreignKey'    => 'follower_id',
					'conditions'    => '',
					'order'         => '',
					'limit'         => '',
					'dependent'     => false
			),
			'Timeline' => array(
					'className'     => 'Timeline',
					'foreignKey'    => 'user_id',
					'conditions'    => '',
					'order'         => '',
					'limit'         => '',
					'dependent'     => false
			),
			'Tweet' => array(
					'className'     => 'Tweet',
					'foreignKey'    => 'user_id',
					'conditions'    => '',
					'order'         => '',
					'limit'         => '',
					'dependent'     => false
			),
			'Favorite' => array(
					'className'     => 'Favorite',
					'foreignKey'    => 'user_id',
					'conditions'    => '',
					'order'         => '',
					'limit'         => '',
					'dependent'     => false
			)
	);
	
	public function beforeSave() {
		if (isset($this->data[$this->alias]['password'])) {
			$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
			$this->data['User']['accesstoken'] = DigestAuthenticate::password(
					$this->data['User']['username'], $this->data['User']['password'], env('SERVER_NAME').time()
			);
		}
		
		return true;
	}
	
	public function updateAccessToken($username){
		$user = $this->find('first',array("conditions" => array("username" =>$username),"recursive" => -1));
		$accesstoken = DigestAuthenticate::password($user["User"]["username"],$user["User"]["password"] , env('SERVER_NAME').time());
		$this->id = $user["User"]["id"];
		$this->saveField("accesstoken",$accesstoken);
		return $accesstoken;
	}
	
	public function updateRegId($username,$reg){
		$user = $this->find('first',array("conditions" => array("username" =>$username),"recursive" => -1));
		$this->id = $user["User"]["id"];
		$this->saveField("reg_id",$reg);
	}
	
	
	
}